//
//  BDNetworking.m
//  BeidouMall
//
//  Created by qie on 16/3/28.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDNetworking.h"

@implementation BDNetworking

+ (BDNetworking *)shareInstance {
    __strong static BDNetworking *sharedManager;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{ // 只会执行一次,且线程安全
        sharedManager = [[BDNetworking alloc] init];
    });
    
    return sharedManager;
}

- (NSString *)baseUrl {
    //return @"http://139.159.32.12:8080/bdcore­web";这个url会崩溃 why?
    return @"http://dev.gzbdmall.com/bdcore-web";
//    return @"http://114.55.74.170:8080/bdcore-web";
//    return @"http://gzbdmall.com/bdcore-web";
}

- (void)postWithUrl:(NSString *)urlString sid:(NSString *)sid method:(NSString *)method parameters:(NSDictionary *)parameters completionHandler:(void (^)(NSObject *, NSError *))completionHandler {
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = method;

    //参数封装
    if (parameters != nil) {
        NSString *result = [self DataTOjsonString:parameters];
        request.HTTPBody = [result dataUsingEncoding:NSUTF8StringEncoding];
    }
   
    //头部
    NSString *compareUrl = [NSString stringWithFormat:@"%@%@",self.baseUrl,Modify_Pwd];
    if ([urlString isEqualToString:compareUrl] && ![BDAccountManagerModel shareInstance].login) {//找回密码
        [request setValue:[BDAccountManagerModel shareInstance].tempAuthorization forHTTPHeaderField:@"Authorization"];
    } else {
        [request setValue:[BDAccountManagerModel shareInstance].authorization forHTTPHeaderField:@"Authorization"];
    }
    [request setValue:@"application/json;charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSURLSession *session = [NSURLSession sharedSession];
    // 由于要先对request先行处理,我们通过request初始化task
    NSURLSessionTask *task = [session dataTaskWithRequest:request
                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                           if (error != nil) {
                                               NSLog(@"error = %@",error);
                                               completionHandler(nil,error);
                                           } else {
                                               NSObject *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                               if ([json isKindOfClass:[NSString class]]) {
                                                   NSString *jsonStr = (NSString *)json;
                                                   NSLog(@"json = %@",json);
                                                   NSDictionary *dic = [self dictionaryWithJsonString:jsonStr];
                                                   if ([dic objectForKey:@"success"]) {
                                                       NSInteger success = [dic[@"success"] integerValue];
                                                       if (success == 1) { // 服务器成功
                                                           if ([dic valueForKey:@"data"] && ![dic[@"data"] isEqual:[NSNull null]]) {
                                                               completionHandler(dic[@"data"],nil);
                                                           } else {
                                                               completionHandler(nil,nil);
                                                           }
                                                       } else {// 服务器自定义错误
                                                           NSString *codeStr = dic[@"code"];
                                                           if (![codeStr isEqual:[NSNull null]] &&
                                                               [codeStr isKindOfClass:[NSString class]] &&
                                                               codeStr != nil) {
                                                               NSError *cutsomError = [self getCustomError:codeStr];
                                                               completionHandler(nil,cutsomError);
                                                           } else {
                                                               NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"服务器未知错误"                                                                      forKey:NSLocalizedDescriptionKey];
                                                               NSError *cutsomError = [[NSError alloc] initWithDomain:@"error" code:9528 userInfo:userInfo];
                                                               completionHandler(nil,cutsomError);
                                                           }
                                                       }
                                                   } else {
                                                       if (dic == nil) {
                                                           NSString *status;
                                                           NSRange range = [jsonStr rangeOfString:@"HTTP Status 401"];//匹配得到的下标
                                                           NSLog(@"range:%@",NSStringFromRange(range));
                                                           if (range.location <= 9999999) {// 找到401错误
                                                               status = [jsonStr substringWithRange:range];//截取范围类的字符串
                                                               NSLog(@"截取的值为：%@",status);
                                                               if ([status isEqualToString:@"HTTP Status 401"]) {
                                                                   NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"登录超时"                                                                      forKey:NSLocalizedDescriptionKey];
                                                                   NSError *cutsomError = [[NSError alloc] initWithDomain:@"logout" code:401 userInfo:userInfo];
                                                                   completionHandler(nil,cutsomError);
                                                               }
                                                           } else {
                                                               NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"json解析失败"                                                                      forKey:NSLocalizedDescriptionKey];
                                                               NSError *cutsomError = [[NSError alloc] initWithDomain:@"json" code:9527 userInfo:userInfo];
                                                               completionHandler(nil,cutsomError);
                                                           }
                                                       }
                                                   }
                                               }
                                           }
                                       }];
    [task resume];
    
}

-(NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"转字符串失败 an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (NSError *)getCustomError:(NSString *)codeStr {
    NSString *message;
    NSInteger code = 0;
    message = NSLocalizedString(codeStr, nil);
    code = 9991;
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:message                                                                      forKey:NSLocalizedDescriptionKey];
    NSError *cutsomError = [[NSError alloc] initWithDomain:@"服务器错误" code:code userInfo:userInfo];
    
    return cutsomError;
}

@end
